<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.senderCode" placeholder="发送人" style="width: 120px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.msgType" style="width: 150px;" class="filter-item" clearable filterable placeholder="消息类型" @keyup.enter.native="handleFilter">
        <el-option
          v-for="item in msgTypeOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-date-picker
        v-model="listQuery.dateValue"
        style="width: 320px;"
        type="datetimerange"
        align="left"
        class="filter-item"
        value-format="yyyy-MM-dd HH:mm:ss"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        @keyup.enter.native="handleFilter"
      />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" size="mini" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" type="info" icon="el-icon-refresh" size="mini" @click="handleReset">
        重置
      </el-button>
      <el-button class="filter-item" type="warning" icon="el-icon-check" size="mini" @click="readAll">
        全部已读
      </el-button>
      <el-button class="filter-item" type="danger" icon="el-icon-plus" size="mini" @click="handleSend">
        发送新消息
      </el-button>
    </div>

    <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
      <el-tab-pane label="全部消息" name="allMessage" />
      <el-tab-pane label="未读消息" is-dot name="unreadMessage" />
      <el-tab-pane label="已读消息" name="readMessage" />
      <el-table :loading="listLoading" :data="list" fit @sort-change="sortChange">
        <el-table-column label="操作" width="80" header-align="center" align="center">
          <template slot-scope="{row}">
            <el-button v-if="row.readFlag === 'N'" type="success" @click="detail(row)">阅读</el-button>
            <el-button v-if="row.readFlag !== 'N'" @click="detail(row)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="senderCode" label="发送人" sortable="custom" width="150" header-align="center" align="left" />
        <el-table-column prop="sendTime" label="发送时间" sortable="custom" width="180" header-align="center" align="center" />
        <el-table-column prop="msgType" label="消息类型" width="100" :formatter="formatter" header-align="center" align="center" />
        <el-table-column prop="msgContent" label="消息内容" min-width="100%" header-align="center" align="left" />
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageNoSize" @pagination="getList" />
    </el-tabs>

    <el-dialog
      :visible.sync="dialogVisible"
      width="400px"
      title="消息详情"
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :label-position="right" label-width="80px" :model="temp" class="form-center">
        <el-form-item label="消息类型">
          <el-select v-model="temp.msgType" disabled>
            <el-option
              v-for="item in msgTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发送人">
          <el-input v-model="temp.senderCode" readonly />
        </el-form-item>
        <el-form-item label="发送时间">
          <el-input v-model="temp.sendTime" suffix-icon="el-icon-date" readonly />
        </el-form-item>
        <el-form-item label="消息内容">
          <el-input v-model="temp.msgContent" autosize type="textarea" readonly />
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="发送新消息" :visible.sync="sendDialogFormVisible" width="400px" :close-on-click-modal="false" :close-on-press-escape="false" center>
      <el-form ref="dataForm" :rules="rules" :model="send" label-position="right" label-width="80px" class="form-center">
        <el-form-item label="消息类型" prop="msgType">
          <el-select v-model="send.msgType">
            <el-option
              v-for="item in msgTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收件人" prop="addresseeCode">
          <el-input v-model="send.addresseeCode" maxlength="64" />
        </el-form-item>
        <el-form-item label="消息内容" prop="msgContent">
          <el-input v-model="send.msgContent" type="textarea" maxlength="1024" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sendDialogFormVisible = false">
          取消
        </el-button>
        <el-button :loading="ajaxSubmiting" type="primary" @click="sendData">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { fetchList, readMessage, readAll, sendMessage } from '@/api/user/messageCenter'
import { setOptionData, valueFormate } from '@/utils/dict'
import Pagination from '@/components/Pagination'

export default {
  name: 'MessageCenter',
  components: { Pagination },
  data() {
    return {
      listLoading: false,
      left: 'left',
      right: 'right',
      total: 10,
      list: [],
      msgTypeOptions: [],
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        sortField: undefined,
        sortOrder: undefined,
        dateValue: [],
        senderCode: '',
        readFlag: '',
        msgType: ''
      },
      temp: {
        senderCode: '',
        sendTime: '',
        msgContent: '',
        msgType: '',
        addresseeCode: ''
      },
      send: {
        msgContent: '',
        msgType: '',
        addresseeCode: ''
      },
      ajaxSubmiting: false,
      activeName: 'allMessage',
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      rules: {
        addresseeCode: [{ required: true, message: '收件人不能为空', trigger: 'change' }],
        msgContent: [{ required: true, message: '消息内容不能为空', trigger: 'change' }],
        msgType: [{ required: true, message: '消息类型不能为空', trigger: 'change' }]
      },
      dateValue: [],
      dialogVisible: false,
      sendDialogFormVisible: false
    }
  },
  computed: {
    ...mapGetters([
      'userMsgChange'
    ]),
    userMsgChange1: function() {
      return this.userMsgChange
    }
  },
  watch: {
    userMsgChange1(newData, oldData) {
      this.handleFilter()
    }
  },
  created() {
    this.handleFilter()
    const optionsMap = new Map()
    optionsMap.set('BASE_MESSAGE_TYPE', this.msgTypeOptions)
    setOptionData(optionsMap)
  },
  methods: {
    sortChange(data) {
      const { prop, order } = data
      this.sortByField(prop, order)
    },
    sortByField(prop, order) {
      if (order === 'ascending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'asc'
      } else if (order === 'descending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'desc'
      } else {
        this.listQuery.sortField = undefined
        this.listQuery.sortOrder = undefined
      }
      this.handleFilter()
    },
    handleClick(tab) {
      if (tab.name === 'unreadMessage') {
        this.listQuery.readFlag = 'N'
      } else if (tab.name === 'readMessage') {
        this.listQuery.readFlag = 'R'
      } else {
        this.listQuery.readFlag = ''
      }
      this.listQuery.pageNo = 1
      this.getList()
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      }, () => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        pageNo: 1,
        pageSize: 10,
        dateValue: [],
        msgType: ''
      }
    },
    formatter(row, column, cellValue, index) {
      return valueFormate(this, column.property, cellValue)
    },
    resetTemp() {
      this.send = {
        msgContent: '',
        msgType: '',
        addresseeCode: ''
      }
    },
    handleSend() {
      this.resetTemp()
      this.sendDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    readAll() {
      this.$confirm('此操作将所有消息设置为已读, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        readAll().then(response => {
          if (response.data) {
            this.$message({
              type: 'success',
              message: '消息全部已读成功!'
            })
          } else {
            this.$message({
              type: 'success',
              message: '没有未读消息!'
            })
          }
          this.$store.dispatch('user/setUserMsgChange')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消全部已读!'
        })
      })
    },
    detail(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogVisible = true
      if (this.temp.readFlag === 'N') {
        this.doReadMessage(this.temp)
      }
    },
    doReadMessage(row) {
      readMessage(row.id).then(response => {
        if (response.data) {
          this.$store.dispatch('user/setUserMsgChange')
        }
      })
    },
    sendData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.ajaxSubmiting = true
          sendMessage(this.send).then(() => {
            this.sendDialogFormVisible = false
            this.ajaxSubmiting = false
            this.$message({
              message: '提交处理成功！',
              type: 'success'
            })
          }, () => {
            this.ajaxSubmiting = false
          })
        }
      })
    }
  }
}
</script>
